# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import models, SUPERUSER_ID
from openerp.tools.translate import _
import os
import generate_ppt

class sale_order(osv.osv):
    _inherit = 'sale.order'
    '''
        下载销售订单对应的PPT方案
    '''
    def get_sale_order_ppt_file(self, cr, uid, ids, context):

        sale_order_obj = self.pool.get("sale.order").browse(cr, uid, ids, context=context)
        # curdirpath = os.path.dirname(__file__)
        # 获取模版的路径
        template_file_path = os.path.join(os.getcwd(),'odoo_addons/common_addons/generate_ppt/static/ppt_templates/dftg_template1.pptx')

        # 设置输出ppt文件的服务器路径,ppt文件命名规则为: 用户ID_订单名称.pptx
        output_file_path = os.path.join(os.getcwd(), 'attachments/ppts/' + str(uid) + '_' + sale_order_obj.name + '.pptx')

        product_dicts = {}
        # 遍历找出所有订单行的产品,字典格式:
        # key->产品id, value->{'product_info':产品对象,'price_unit':订单行中的产品售价}
        for order_line_obj in sale_order_obj.order_line:
            temp_product_dict = {}
            temp_product_dict['product_info'] = order_line_obj.product_id
            temp_product_dict['price_unit'] = order_line_obj.price_unit
            product_dicts.setdefault(order_line_obj.product_id.id, temp_product_dict)
        generate_ppt.analyze_ppt(template_file_path, output_file_path, product_dicts)

        #设置ppt的url获取路径
        ppt_url = "/PPT/get_ppt/"+str(uid) + '_' + sale_order_obj.name

        # 返回一个url的action去直接下载方案
        return {
            'type': 'ir.actions.act_url',
            'url': ppt_url,
            'target': 'new',
        }
